<template>
  <view class="tetris-container">
    <!-- 游戏主画布 -->
    <canvas 
      canvas-id="gameCanvas" 
      :style="{width: canvasWidth + 'px', height: canvasHeight + 'px'}"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd" style="border: solid;"
    ></canvas>
    
    <!-- 下一个方块预览 -->
    <view class="next-block">
      <text>下一个：</text>
      <canvas canvas-id="nextCanvas" :style="{width: '300rpx', height: '200rpx'}" :width="blockSize * 4" :height="blockSize * 4"></canvas>
    </view>
    
    <!-- 分数显示 -->
    <view class="score">分数：{{ score }}</view>
    
    <!-- 操作按钮 -->
    <view class="control-buttons">
      <button class="btn" @click="moveHorizontal(-1)">←</button>
      <button class="btn" @click="rotateBlock">↻</button>
      <button class="btn" @click="moveDown">↓</button>
      <button class="btn" @click="moveHorizontal(1)">→</button>
    </view>

    <!-- 游戏结束提示 -->
    <view v-if="gameOver" class="game-over">
      <text class="game-over-text">游戏结束！</text>
      <button class="restart-btn" @click="initGame">重新开始</button>
    </view>
  </view>
</template>

<script>
// 方块形状定义
const SHAPES = [
  [[1, 1, 1, 1]], // I
  [[1, 1], [1, 1]], // O
  [[1, 1, 1], [0, 1, 0]], // T
  [[1, 1, 1], [1, 0, 0]], // L
  [[1, 1, 1], [0, 0, 1]], // J
  [[1, 1, 0], [0, 1, 1]], // S
  [[0, 1, 1], [1, 1, 0]]  // Z
];

// 颜色定义
const COLORS = ['#00f0f0', '#f0f000', '#a000f0', '#f0a000', '#0000f0', '#00f000', '#f00000'];

export default {
  props: {
    // 游戏难度（下落速度）
    level: {
      type: Number,
      default: 1
    }
  },
  
  data() {
    return {
      canvasWidth: 300,
      canvasHeight: 600,
      blockSize: 30,
      score: 0,
      gameMap: [],
      currentBlock: null,
      nextBlock: null,
      ctx: null,
      nextCtx: null,
      touchStartX: 0,
      touchStartY: 0,
      gameOver: false,
      intervalId: null
    };
  },

  mounted() {
    // this.initGame();
    // this.gameLoop();
  },

  methods: {
    initGame() {
		this.gameOver=false
		this.gameLoop();
      // 初始化游戏地图
      this.gameMap = Array(20).fill().map(() => Array(10).fill(0));
      
      // 获取上下文
      this.ctx = uni.createCanvasContext('gameCanvas', this);
      this.nextCtx = uni.createCanvasContext('nextCanvas', this);
      
      // 生成初始方块
      this.currentBlock = this.createRandomBlock();
      this.nextBlock = this.createRandomBlock();
      this.drawBlock();
    },

    createRandomBlock() {
      const type = Math.floor(Math.random() * SHAPES.length);
      return {
        shape: SHAPES[type],
        color: COLORS[type],
        x: 4,
        y: 0
      };
    },

    drawBlock() {
      // 清空画布
      this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
      
      // 绘制地图
      for (let y = 0; y < 20; y++) {
        for (let x = 0; x < 10; x++) {
          if (this.gameMap[y][x]) {
            this.ctx.setFillStyle(this.gameMap[y][x]);
            this.ctx.fillRect(x * this.blockSize, y * this.blockSize, 
              this.blockSize - 1, this.blockSize - 1);
          }
        }
      }

      // 绘制当前方块
      this.currentBlock.shape.forEach((row, y) => {
        row.forEach((cell, x) => {
          if (cell) {
            this.ctx.setFillStyle(this.currentBlock.color);
            this.ctx.fillRect(
              (this.currentBlock.x + x) * this.blockSize,
              (this.currentBlock.y + y) * this.blockSize,
              this.blockSize - 1,
              this.blockSize - 1
            );
          }
        });
      });

      this.ctx.draw();

      // 绘制下一个方块预览
      this.nextCtx.clearRect(0, 0, 100, 100);
      const previewSize = this.blockSize * 4;
      const offsetX = (150 - this.nextBlock.shape[0].length * this.blockSize) / 2;
      const offsetY = (100 - this.nextBlock.shape.length * this.blockSize) / 2;

      this.nextBlock.shape.forEach((row, y) => {
        row.forEach((cell, x) => {
          if (cell) {
            this.nextCtx.setFillStyle(this.nextBlock.color);
            this.nextCtx.fillRect(
              offsetX + x * this.blockSize,
              offsetY + y * this.blockSize,
              this.blockSize - 1,
              this.blockSize - 1
            );
          }
        });
      });
      this.nextCtx.draw();
    },

    moveDown() {
      this.currentBlock.y++;
      if (this.checkCollision()) {
        this.currentBlock.y--;
        this.fixBlock();
        this.checkLines();
        if (this.checkGameOver()) {
          this.gameOver = true;
          clearInterval(this.intervalId);
          return;
        }
        this.currentBlock = this.nextBlock;
        this.nextBlock = this.createRandomBlock();
      this.drawBlock();
      }
      this.drawBlock();
    },

    checkCollision() {
      return this.currentBlock.shape.some((row, dy) => {
        return row.some((cell, dx) => {
          let newX = this.currentBlock.x + dx;
          let newY = this.currentBlock.y + dy;
          return (
            cell &&
            (newY >= 20 || newX < 0 || newX >= 10 || this.gameMap[newY]?.[newX])
          );
        });
      });
    },

    fixBlock() {
      this.currentBlock.shape.forEach((row, y) => {
        row.forEach((cell, x) => {
          if (cell) {
            this.gameMap[this.currentBlock.y + y][this.currentBlock.x + x] = 
              this.currentBlock.color;
          }
        });
      });
    },

    checkLines() {
      let lines = 0;
      for (let y = 19; y >= 0; y--) {
        if (this.gameMap[y].every(cell => cell)) {
          this.gameMap.splice(y, 1);
          this.gameMap.unshift(Array(10).fill(0));
          lines++;
          y++;
        }
      }
      if (lines > 0) {
        this.score += lines * 100;
        this.$emit('score-change', this.score);
      }
    },

    handleTouchStart(e) {
      this.touchStartX = e.touches[0].clientX;
      this.touchStartY = e.touches[0].clientY;
    },

    handleTouchMove(e) {
      // 阻止页面滚动
      e.preventDefault();
    },

    handleTouchEnd(e) {
      const deltaX = e.changedTouches[0].clientX - this.touchStartX;
      const deltaY = e.changedTouches[0].clientY - this.touchStartY;

      if (Math.abs(deltaX) > 30) {
        this.moveHorizontal(deltaX > 0 ? 1 : -1);
      } else if (deltaY < -30) {
        this.rotateBlock();
      } else if (deltaY > 30) {
        this.dropFast();
      }
    },

    moveHorizontal(direction) {
      this.currentBlock.x += direction;
      if (this.checkCollision()) {
        this.currentBlock.x -= direction;
      }
      this.drawBlock();
    },

    rotateBlock() {
      const rotated = this.currentBlock.shape[0].map((_, i) =>
        this.currentBlock.shape.map(row => row[i]).reverse()
      );
      const originalShape = this.currentBlock.shape;
      this.currentBlock.shape = rotated;
      if (this.checkCollision()) {
        this.currentBlock.shape = originalShape;
      }
      this.drawBlock();
    },

    dropFast() {
      while (!this.checkCollision()) {
        this.currentBlock.y++;
      }
      this.currentBlock.y--;
      this.fixBlock();
      this.checkLines();
      this.currentBlock = this.nextBlock;
      this.nextBlock = this.createRandomBlock();
      this.drawBlock();
      this.drawBlock();
    },

    gameLoop() {
      this.intervalId = setInterval(() => {
        if (!this.gameOver) this.moveDown();
      }, 1000 / this.level);
    },
    
    checkGameOver() {
      return this.nextBlock.shape.some((row, dy) => {
        return row.some((cell, dx) => {
          return cell && this.gameMap[dy]?.[dx + 4];
        });
      });
    }
  }
};
</script>

<style scoped>
.tetris-container {
  position: relative;
  background: #f0f0f0;
  padding: 20rpx;
}

.next-block {
  position: absolute;
  right: 20rpx;
  top: 20rpx;
  background: white;
  width: 350rpx;
  /* padding-r */
}

.score {
  position: absolute;
  top: 20rpx;
  left: 20rpx;
  font-size: 32rpx;
  color: #333;
}
  .control-buttons {
    position: absolute;
    bottom: 40rpx;
    right: -175rpx;
    /* transform: translateX(-50%); */
    display: flex;
	flex-direction: column;
    gap: 20rpx;
    flex-wrap: wrap;
    min-width: 480rpx;
    justify-content: center;
  }

  .btn {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    background: #4a90e2;
    color: white;
    font-size: 32rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4rpx 8rpx rgba(0,0,0,0.1);
  }

  .game-over {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: rgba(0,0,0,0.8);
    padding: 40rpx;
    border-radius: 20rpx;
    text-align: center;
  }

  .game-over-text {
    color: white;
    font-size: 48rpx;
    margin-bottom: 30rpx;
    display: block;
  }

  .restart-btn {
    background: #f0a000;
    color: white;
    font-size: 32rpx;
    border-radius: 40rpx;
    padding: 20rpx 40rpx;
  }
</style>